package shukka;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import common.Customer;
import common.Item;

import db.DBManager;

public class DeliServlet extends HttpServlet {
	
	private final String URL_FOR_SEND = "http://192.168.3.190:8080/Delivery/Accept";//問い合わせ先の URL 

	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		perform(req,resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		perform(req,resp);
	}
	
	private void perform(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException{
		resp.setContentType("text/html;charset=UTF-8");
		req.setCharacterEncoding("UTF-8");
		StringBuffer msg = new StringBuffer();//メッセージdeli.jspに表示する。
		
		Connection con = null;
		con =  DBManager.getConnection();
		//①配達済みフラグが「0」のモノをＤＢ内のreceiptテーブルを検索する。
		String sql = "select * from receipt where deliver_flag = 0;";
		
		System.out.println(sql);//テスト用
		
		try{
				Statement stm = null;
				ResultSet rs = null;
				PreparedStatement ps = null;//商品コード検索時に使用
			
				con = DBManager.getConnection();//DBManeger
				stm = con.createStatement();
				rs = stm.executeQuery(sql);
			
				ArrayList<Deliver> receipt_list = new ArrayList<Deliver>();
				while(rs.next()){
					Deliver receipt = new Deliver();
				
					receipt.setS_number(rs.getString("num"));
					receipt.setS_count("1");
					receipt.setS_date(rs.getString("deliver"));
					receipt.setS_kind("001");
					receipt.setD_code(rs.getString("customer_code"));
				
					receipt_list.add(receipt);
				}
			
				//② 納品請求情報(receiptテーブル)より取得した顧客コードを使って、Customerクラスのfind_by_code(String code)より顧客情報を取得する。
				List<Customer> customer_list = new ArrayList<Customer>();
			
				//カスタマーのオブジェクトを入れる。
				for(int i=0;i<receipt_list.size();i++){
					Deliver info = receipt_list.get(i);
					System.out.println(info.getD_code());
					customer_list.add(Customer.find_by_code(info.getD_code()));
				}
			
				//③検索した情報を使って配送データを作成する
				URL url = new URL(URL_FOR_SEND); 
				
				PrintWriter out =null;
			 
				System.out.println("ループ回数" + receipt_list.size());
		
				for(int i=0;i<receipt_list.size();i++){
					//システムに接続する 
					HttpURLConnection connection = (HttpURLConnection)url.openConnection(); 
					//POST メソッドで送信する準備 
					connection.setRequestMethod("POST"); 
					connection.setDoOutput(true); 
					out = new PrintWriter(connection.getOutputStream()); 
					
					StringBuffer param = new StringBuffer(); 
					
					Customer customer = customer_list.get(i);
					Deliver  recepit = receipt_list.get(i);
			
					System.out.println(customer.getCode());
					
					//お届け先情報 
					param.append("d_code=" + customer.getCode()); //省略可 
					param.append("&d_tel=" + customer.getTel()); 
					param.append("&d_postcode=" + customer.getPostcode()); 
					param.append("&d_address=" + customer.getAddress()); 
					param.append("&d_name=" + customer.getName()); 
					//ご依頼主情報 
					param.append("&c_code=" + "123456654321"); 
					param.append("&c_tel=" + "091-5234-5525"); 
					param.append("&c_postcode=" + "860-1123"); //省略可 
					param.append("&c_address=" + "大分県大分市酉月関園111番地"); //省略可 
			 
			 
				 
					//④商品情報を取得するため納品請求情報(receiptテーブル)より取得した納品番号を使って、納品請求明細(receipt_itemテーブル)を検索する。

					StringBuffer set = new StringBuffer();//SQL文作成使うStringBuffer
						set.append("receipt_num = '" + recepit.getS_number() + "'");
					
						String add = set.toString();//StringBufferをString型に変更
						sql="select * from receipt_item where "+ add +";";
				
						System.out.println("納品請求明細を検索するSQL\n"+sql);//テスト用
						rs = stm.executeQuery(sql);
				
						StringBuffer count = new StringBuffer();
						int int_s_count=0;
						while(rs.next()){
							int_s_count++;
						}
						String s_count = String.valueOf(int_s_count);
						if(int_s_count<10){//10以下の場合0を付けてString型に変更
							count.append("0"+int_s_count);
							s_count = count.toString();
						}
						//出荷情報 
						param.append("&s_number=" + recepit.getS_number()); 
						param.append("&s_count=" + s_count); 
				 
						String s_date = recepit.getS_date().replaceAll("-","");
						param.append("&s_date=" + s_date); //省略可 
						param.append("&s_kind=" + "001"); //省略可 
				 
						sql="select * from receipt_item where "+ add +";";
						rs = stm.executeQuery(sql);
						while(rs.next()){
							param.append("&i_number=" + rs.getInt("num")); 
							param.append("&i_code=" + rs.getString("item_code")); 
					
							Item item =Item.find_by_code(rs.getString("item_code"));
					
							param.append("&i_name1=" + item.getName()); //商品名
							param.append("&i_name2=" + item.getSize()); //規格
							param.append("&i_suu=" + rs.getInt("orders")); //一つの商品に対する注文数
						}
						System.out.println("送信するデータ\n"+param.toString());
						out.print(param.toString());
						out.flush(); 
						System.out.println("HttpURLConnection" +connection.getResponseCode());
						//結果を取得する 
						if (connection != null) { 
							if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) { 
								//送信完了 
								sql="update receipt SET deliver_flag = 1 where num = "+ recepit.getS_number() +";";
								System.out.println(sql);
								ps = con.prepareStatement(sql);
								ps.executeUpdate();
								
								System.out.println("OK");
							} 
							else { 
								//送信失敗 
								msg.append("納品番号"+recepit.getS_number()+"のデータの送信に失敗しました。");
								System.out.println("NG");
							} 
						}
						if (connection != null) { 
							connection.disconnect(); 
						} 
				}//送信のループ文終了
				
				if(msg.length()==0){
					msg.append("配送データ送信完了しました。");
				}
				
				req.setAttribute("msg", msg.toString());
				RequestDispatcher dispatcher = req.getRequestDispatcher("/operator/deli.jsp");
				dispatcher.forward(req, resp);
				
				//後処理 
				if (out != null) { 
					out.close(); 
					con.close();
					stm.close();
					ps.close();
					rs .close();
				} 
		}//try閉じる
		
		catch (MalformedURLException e1) { 
			 e1.printStackTrace(); 
		} 
		catch (ProtocolException e1) { 
			 e1.printStackTrace(); 
		} 
		catch (IOException e1) { 
			 e1.printStackTrace(); 
		
		}
		catch(NullPointerException e){
			e.printStackTrace();
			msg.append("未送信の配送データは現在ありません。");
			
			req.setAttribute("msg", msg.toString());
			RequestDispatcher dispatcher = req.getRequestDispatcher("/operator/deli.jsp");
			dispatcher.forward(req, resp);
		}
		catch(SQLException e){
			e.printStackTrace();
		}
	}
}
